package com.hinnotek.warehouse.ui

import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.activity.viewModels
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.google.gson.Gson
import com.hinnotek.warehouse.BR
import com.hinnotek.warehouse.R
import com.hinnotek.warehouse.bean.MachineAccountBean
import com.hinnotek.warehouse.bean.MachineListBean
import com.hinnotek.warehouse.databinding.*
import com.hinnotek.warehouse.dialog.Dialogs
import com.hinnotek.warehouse.utils.*
import com.hinnotek.warehouse.viewmodel.StockInViewModel
import com.lee.common.adapter.binding.SimpleBindingAdapter
import com.lee.common.base.BaseActivity
import com.lee.common.ext.getArg
import com.lee.common.ext.init
import com.lee.common.observer.DefaultObserver
import com.lee.common.utils.*
import dagger.hilt.android.AndroidEntryPoint
import timber.log.Timber
import java.sql.Time

/**
 * 借用 -> 借用单设备列表
 */
@Route(path = ACTIVITY_NONCE_BORROWING_LIST)
@AndroidEntryPoint
class NonceBorrowingListActivity : BaseActivity<ActivityNonceBorrowingListBinding>() {

    private lateinit var adapter: SimpleBindingAdapter<MachineListBean, ItemMachineListLayoutBinding>
    private val viewModel by viewModels<StockInViewModel>()

    var machineAccountBean: MachineAccountBean? = null
    var footView: View? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        machineAccountBean = intent.getSerializableExtra(MACHINE_CONTENT_LIST) as MachineAccountBean
        setContentView(R.layout.activity_nonce_borrowing_list)
        setTitle("借用单设备列表")
        bindingView.vm = viewModel
        bindingView.executePendingBindings()
        viewModel.attachLoading(loadingState)
        viewModel.dialogMsg.observe(this, DefaultObserver(this))
        viewModel.autoRefresh()
        bindingView.machineData = machineAccountBean
        viewModel.setParameters(intent.getIntExtra("applyId", 0))
        addCompleteView()
    }

    override fun initVew() {
        adapter = SimpleBindingAdapter(
            R.layout.item_machine_list_layout,
            ArrayList(),
            BR.machineList
        )
        bindingView.recycler.init()
        bindingView.recycler.adapter = adapter

        //状态布局切换
        emptyView.adapter = adapter
        viewModel.isEmpty.observe(this, Observer {
            emptyView.values(it)
        })
        emptyView.getErrView().setOnClickListener {
            viewModel.refresh()
        }

        //底部审核layout
        if (machineAccountBean?.approvalState == 1) {
            val bottomBind = DataBindingUtil.inflate<BottomApplyingLayoutBinding>(
                layoutInflater,
                R.layout.bottom_applying_layout,
                null,
                false
            )
            bottomBind.agree.setOnClickListener {//同意
                toApproval(2)
            }
            bottomBind.reject.setOnClickListener {//拒绝
                Dialogs(this).showCurrency5 {
                    toApproval(3)
                }
            }
            footView = bottomBind.root
            adapter.addFooterView(bottomBind.root)
        }

        //添加adapter
        adapter.addListener { binding, item ->
            binding.toScan.setOnClickListener {
                Skipping.navScan(
                    machineAccountBean?.wareId ?: 0, item.applyDeviceId, WAREHOUSE_TYPE_3, this@NonceBorrowingListActivity
                )
            }
            binding.root.setOnClickListener {
                if (machineAccountBean?.approvalState != WAREHOUSE_APPROVED)
                    return@setOnClickListener
                if (machineAccountBean?.goodsType ?: "" == WAREHOUSE_GOODS_TYPE_1)
                    return@setOnClickListener
                Skipping.start(
                    ACTIVITY_NONCE_BORROWING_DETAIL, "applyDeviceId", item.applyDeviceId,
                    MACHINE_CONTENT_LIST, machineAccountBean,
                    MACHINE_DETAIL_LIST, item, this
                )
            }
        }
    }

    override fun onResume() {
        //未完成
        if (machineAccountBean?.completeState == 1) {
            viewModel.isComplete()
        }
        super.onResume()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (resultCode==200){
            viewModel.autoRefresh()
        }
        super.onActivityResult(requestCode, resultCode, data)
    }

    /**
     * adapter 添加手动完成view
     */
    private fun addCompleteView() {
        if (machineAccountBean?.goodsType == WAREHOUSE_GOODS_TYPE_1) {
            return
        }
        if (machineAccountBean?.completeState == WARE_COMPLETE_STATE) {
            return
        }
        if (machineAccountBean?.approvalState == WAREHOUSE_APPROVED) {
            if (adapter.hasFooterLayout()) {
                adapter.removeAllFooterView()
            }
            val bottomBind = DataBindingUtil.inflate<BottomCompleteLayoutBinding>(
                layoutInflater, R.layout.bottom_complete_layout,
                null, false
            )
            bottomBind.complete.setOnClickListener {//完成
                Dialogs(this).showCurrency3("是否完成此仓库单?") { dialog, which ->
                    viewModel.toClickComplete()
                }
            }
            adapter.addFooterView(bottomBind.root)
        }
    }

    /**
     * 发送审核数据
     */
    private fun toApproval(state: Int) {
        viewModel.approvalState = state
        viewModel.approvalApplyId = machineAccountBean?.applyId ?: 0
        viewModel.refusalReasons = ""
        viewModel.loadData()
    }


    override fun setData() {
        //加载数据
        viewModel.stockInListPage.observe(this, Observer {
            for (machineListBean in it) {
                machineListBean.approvalState = machineAccountBean?.approvalState ?: 1
                machineListBean.goodsType = machineAccountBean?.goodsType ?: ""
            }
            adapter.addAll(it, viewModel.isFirst)
        })

        //审核
        viewModel.approvalData.observe(this, Observer {
            if (viewModel.isSuccess) {
                ToastUtils.showLong("审核成功")
                machineAccountBean?.approvalState = WAREHOUSE_APPROVED
                for (datum in adapter.data) {
                    datum.approvalState = WAREHOUSE_AUDIT
                }

                addCompleteView()
            }
        })

        //完成状态监听
        viewModel.isCompleteData.observe(this, {
            if (viewModel.isSuccess) {
                complete()
            }
        })
        //手动完成此单
        viewModel.clickCompleteData.observe(this, Observer {
            if (viewModel.isSuccess) {
                ToastUtils.showLong("借用成功")
                adapter.removeAllFooterView()
                complete()
            }
        })

    }

    private fun complete() {
        machineAccountBean?.completeState = 2
        bindingView.textView28.text =
            String.format(getString(R.string.complete_StateStr), "已完成")
    }

}